package com.example.demo.controller;
/*
 * 李洲 2020030654A1213
 * 2024.05.24
 */
import com.example.demo.model.Event;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.beans.PropertyEditorSupport;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Controller
@RequestMapping("/events")
public class EventController {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
            }

            @Override
            public String getAsText() {
                LocalDateTime value = (LocalDateTime) getValue();
                return value != null ? value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) : "";
            }
        });
    }

    @PostMapping
    public String createEvent(@ModelAttribute Event event) {
        // 处理逻辑，例如将事件保存到数据库
        System.out.println("Event Name: " + event.getName());
        System.out.println("Event Date: " + event.getDate());
        return "eventCreated"; // 返回视图名称
    }

    @RequestMapping("/new")
    public String newEvent() {
        return "newEvent"; // 返回创建事件的视图
    }
}
